import java.io.UnsupportedEncodingException;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Initialize {

	private int portNum;

	public synchronized void initializeSelf() throws UnknownHostException,
			NoSuchAlgorithmException, UnsupportedEncodingException {

		NodeTriple selfNodeTriple = new NodeTriple();

		SelfInfo.listeningSocket = this.setupSocket();

		selfNodeTriple.ip = SelfInfo.listeningSocket.getLocalAddress();
		selfNodeTriple.port = SelfInfo.listeningSocket.getLocalPort();

		SelfInfo.nodeTriple = selfNodeTriple;

		SelfInfo.sendSocket = this.setupSocket();

		selfNodeTriple.nodeID = this.generateIDforSelf();
		
		initializeBucketList();
		
		TimedOperations operations = new TimedOperations();
		Thread timedCleanup = new Thread(operations);
		timedCleanup.start();
		


	}

	private synchronized DatagramSocket setupSocket() throws UnknownHostException {
		DatagramSocket socket = null;
		this.portNum = (int) (Math.random() * 9999) + 1000;
		if ((portNum > 9999) && (portNum < 1000)) {
			this.setupSocket();
		}

		try {
			socket = new DatagramSocket(this.portNum,
					InetAddress.getLocalHost());

		} catch (SocketException e) {
			System.out.println("Port: " + portNum
					+ " already taken, trying one more");
			setupSocket();
		}
		

		return socket;
	}

	private synchronized String convertToHex(byte[] data) {
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < data.length; i++) {
			int halfbyte = (data[i] >>> 4) & 0x0F;
			int two_halfs = 0;
			do {
				if ((0 <= halfbyte) && (halfbyte <= 9))
					buf.append((char) ('0' + halfbyte));
				else
					buf.append((char) ('a' + (halfbyte - 10)));
				halfbyte = data[i] & 0x0F;
			} while (two_halfs++ < 1);
		}
		return buf.toString();
	}

	public synchronized String generateIDforSelf() throws NoSuchAlgorithmException,
			UnsupportedEncodingException {
		String textForHasing = SelfInfo.nodeTriple.ip + ""
				+ SelfInfo.nodeTriple.port;
		MessageDigest md;
		md = MessageDigest.getInstance("SHA-1");
		byte[] sha1hash = new byte[40];
		md.update(textForHasing.getBytes("iso-8859-1"), 0,
				textForHasing.length());
		sha1hash = md.digest();
		
		return convertToHex(sha1hash);
	}
	
	public synchronized void initializeBucketList(){
		
		//TODO: Create bucket list. 
		
	}
}
